const router = require('koa-router')();  //koa-router是一个函数，要调用一下
const userService = require('../controllers/mySqlControll.js')
const jwt = require('../untils/jwt.js')


const reg = /^1[3-9]\d{9}$/;  //手机号的测试
// 登录接口
router.post('/login', async (ctx, next) => {
  let { username, password } = ctx.request.body
  // console.log(username);
  // console.log(password);
  try {
    const result = await userService.userLogin(username, password)
    // console.log(result[0].user_id);
    // if (result.length) {
    // }

    if (result.length) { //假设数据检验成功
      let token = jwt.sign({ username: username, password: password, admin: true })
      // 这行代码使用jsonwebtoken库中的jwt.sign方法来生成一个JWT Token。
      // 在这里，我们传入了一个包含id、username和admin字段的对象作为payload，
      // 然后使用默认的私钥（通常应该使用更加安全的私钥）对其进行签名。生成的token将被存储在变量token中。
      // console.log(token);
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result[0].user_id,
        token: token,
        msg: '登录成功'
      }
    } else {
      if (username === '' || password === '') {
        ctx.body = {
          msgType: '8002',
          code: 0,
          data: 'error',
          msg: '输入框不能为空'
        }
      } else {
        ctx.body = {
          msgType: '8002',
          code: 0,
          data: 'error',
          msg: '账号或密码错误'
        }
      }
    }
    // console.log(user);
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器错误'
    }
  }
})


// 注册接口
router.post('/register', async (ctx, next) => {
  const { username, password, phone, againPassword } = ctx.request.body
  // console.log(username);
  // console.log(password);
  // console.log(phone);
  if (!username || !password || !phone) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      msg: '输入框不能为空'
    }
    return
  }

  if (!reg.test(phone)) {  //手机号的测试,输入正确的号
    ctx.body = {
      msgType: '8002',
      code: 0,
      msg: '手机号码错误'
    }
    return
  }

  if (againPassword !== password) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      msg: '密码不一致'
    }
    return
  }

  try {
    const findUser = await userService.userSearch(phone)
    // console.log(findUser);
    if (!!findUser.length) {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: 'err',
        msg: '用户已存在'
      }
    }
    else {
      await userService.userRegister([username, password, phone]).then(res => {
        // console.log(res);
        if (res.affectedRows !== 0) {
          ctx.body = {
            msgType: '8000',
            code: 0,
            data: 'ok',
            msg: '注册成功'
          }
        } else {
          ctx.body = {
            msgType: '8002',
            code: 0,
            data: 'error',
            msg: '注册失败'
          }
        }
      })


    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }

})


// 获取菜单数据
router.get('/', jwt.verify(true), async (ctx) => {
  // console.log(1);
  try {
    const result = await userService.giveFormData()
    // console.log(result);
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '欢迎您使用系统'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 获取user中的数据
router.get('/userListName', jwt.verify(true), async (ctx, next) => {
  // console.log(1);
  try {
    // const userLists = await userService.getUserList()
    const result = await userService.getAnnotations()
    // console.log(result);
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '查询成功'
      }
    }

  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 用在app中，通过id获取用户信息
router.get('/getUserFromId', jwt.verify(true), async (ctx, next) => {
  const {user_id}=ctx.request.query
  try {
    const result = await userService.getUserFromId(user_id)
    // console.log(result);
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '查询成功'
      }
    }

  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 用在管理系统中，通过id获取用户信息
router.post('/getDetailUserData', jwt.verify(true), async (ctx, next) => {
  const {user_id}=ctx.request.body
  // console.log(user_id);
  try {
    const result = await userService.getUserFromId(user_id)
    // console.log(result);
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '查询成功'
      }
    }

  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})



// 获取用户的信息
router.get('/userList', jwt.verify(true), async (ctx, next) => {
  // console.log(1);
  try {
    const result = await userService.getUserList()
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '查询成功'
      }
    }

  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 修改用户的信息
router.post('/changeUserData', jwt.verify(true), async (ctx, next) => {
  const { userName, password, phone, userType, sex, avatar, points, userid } = ctx.request.body
  if (userName == '' || password == '' || phone == '' || userType == '' || sex == '' || avatar == '') {
    // alert('请填写完整的表单信息');
    ctx.body = {
      code: 0,
      msgType: '8002',
      msg: '请填写完整的表单信息'
    }
    return;
  }

  if (!reg.test(phone)) {
    ctx.body = {
      code: 0,
      msgType: '8002',
      msg: '请输入正确的电话号码格式'
    }
    return;
  }
  try {
    const result = await userService.changeUserData(userName, password, phone, userType, sex, avatar, points, userid)
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '修改成功'
      }
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: result,
        msg: '修改失败'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})


// 增加用户的信息
router.post('/addUserData', jwt.verify(true), async (ctx, next) => {
  const { userName, password, phone, userType, sex, avatar, points } = ctx.request.body
  // console.log(userName, password, phone, userType, sex, points);
  // console.log(username);
  // console.log(password);
  // console.log(phone);
  const reg = /^1[3-9]\d{9}$/;  //手机号的测试
  if (!userName || !password || !phone) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      msg: '输入框不能为空'
    }
    return
  }

  if (!reg.test(phone)) {  //手机号的测试,输入正确的号
    ctx.body = {
      msgType: '8002',
      code: 0,
      msg: '手机号码错误'
    }
    return
  }
  try {
    const findUser = await userService.userSearch(phone)
    // console.log(findUser);
    if (!!findUser.length) {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: 'err',
        msg: '用户已存在'
      }
      return
    }
    else {
      // console.log(1);
      try {
        await userService.addUserInformation([userName, password, phone, userType, sex, avatar, points]).then(res => {
          // console.log(res);
          if (res.affectedRows !== 0) {
            ctx.body = {
              msgType: '8000',
              code: 0,
              data: 'ok',
              msg: '增加成功'
            }
          } else {
            ctx.body = {
              msgType: '8002',
              code: 0,
              data: 'error',
              msg: '增加失败'
            }
          }
        })
      } catch (error) {
        ctx.body = {
          msgType: '8002',
          code: 1,
          data: error,
          msg: '服务器异常'
        }
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }

})

// 查找用户的信息
router.post('/findUserFromName', async (ctx, next) => {
  const { searchName, selectioned } = ctx.request.body
  try {
    // console.log(searchName, selectioned);
    await userService.findName(searchName, selectioned).then(res=>{
      // console.log(res);
      // ctx.status=8000
      if (!!res.length) {
        ctx.body = {
          msgType:'8000',
          code: 0,
          data: res,
          msg: '查找成功',
        }
      }else{
        ctx.body = {
          msgType:'8002',
          code: 0,
          data: res,
          msg: '查找失败',
        }
      }
      
    })
  } catch (error) {
    ctx.body = {
      code: 0,
      data: error,
      msg: '服务器异常',
    }
  }
})

// 删除用户信息
router.post('/deleteUser', jwt.verify(true), async (ctx, next) => {
  const { userid} = ctx.request.body; // 获取前端发送的userids数组
  // console.log(userid); // 打印出前端发送的userids数组
  try {
    const results = await Promise.all(userid.map(userid => userService.deleteUser(userid))); // 遍历userids数组，对每个userid执行删除操作并返回Promise数组
    // console.log(results);
    const affectedRows = results.reduce((total, result) => total + result.affectedRows, 0); // 获取所有删除操作受影响的行数总和
    // console.log(affectedRows);
    if (affectedRows !== 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: 'ok',
        msg: '删除成功'
      };
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: 'error',
        msg: '删除失败'
      };
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    };
  }
});

module.exports = router